package com.lagou.handler;

import com.lagou.client.RpcRequest;
import com.lagou.client.RpcResponse;
import com.lagou.utils.InterfaceMapUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception {
        System.out.println("服务端收到请求");
        String requestId = request.getRequestId();
        String interfaceName = request.getInterfaceName();
        String methodName = request.getMethodName();
        Class<?>[] paramTypes = request.getParamTypes();
        Object[] prams = request.getPatams();
        Class<?> clazz = InterfaceMapUtils.interfaceMap.get(interfaceName);
        Object instance = clazz.newInstance();
        Method method = clazz.getMethod(methodName, paramTypes);
        Object invoke = method.invoke(instance, prams);
        RpcResponse response = new RpcResponse();
        response.setRequestId(requestId);
        response.setData(invoke);
        ctx.writeAndFlush(response);
        System.out.println("服务端处理请求完毕");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
